package com.gongpingjialoan.activity.main;

import android.content.Intent;
import android.os.Bundle;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import com.gongpingjialoan.R;
import com.gongpingjialoan.activity.car.BuyCarVipActivity;
import com.gongpingjialoan.adapter.SubScribeAdapter;
import com.gongpingjialoan.api.API;
import com.gongpingjialoan.network.NetDataJson;
import com.gongpingjialoan.widget.LoadingDialog;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/5/26.
 */
public class SubscribeActivity extends BaseActivity implements AdapterView.OnItemClickListener, NetDataJson.OnNetDataJsonListener, PullToRefreshBase.OnRefreshListener<ListView>, PullToRefreshBase.OnLastItemVisibleListener {

    private PullToRefreshListView pullToRefreshListView;

    private ImageView nodataImageView;

    private ListView listView;

    private View footView;

    private NetDataJson mNetDataJson;

    private NetDataJson deleteNetDataJson;

    private LoadingDialog loadingDialog;

    private SubScribeAdapter adapter;

    public int mPage;

    public boolean mIsLoadingMore = true;

    public boolean mHasMore;

    public boolean isRefresh;

    List<JSONObject> list;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_subscribe);
        setTitle("订阅记录");
        loadingDialog = new LoadingDialog(this);

        footView = LayoutInflater.from(this).inflate(R.layout.listview_footview, null);
        nodataImageView = (ImageView) findViewById(R.id.no_info);
        pullToRefreshListView = (PullToRefreshListView) findViewById(R.id.listview);
        pullToRefreshListView.setScrollingWhileRefreshingEnabled(false);
        pullToRefreshListView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        pullToRefreshListView.setOnRefreshListener(this);
        pullToRefreshListView.setOnLastItemVisibleListener(this);
        list = new ArrayList<>();
        adapter = new SubScribeAdapter(this);
        listView = pullToRefreshListView.getRefreshableView();
        listView.addFooterView(footView);
        listView.setAdapter(adapter);
        listView.removeFooterView(footView);
        listView.setOnItemClickListener(this);

        mNetDataJson = new NetDataJson(this);
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                pullToRefreshListView.setRefreshing();
            }
        }, 300);
//        StepRecord.recordStep(this, "Cd1_history_sellcar", "");
    }

    private void refresh() {
        mPage = 1;
        mHasMore = true;
        isRefresh = true;
        nodataImageView.setVisibility(View.GONE);
        updateData();

    }


    private void updateData() {
        mNetDataJson.cancelTask();
        mNetDataJson.setUrl(API.subscribelist);
        mNetDataJson.request("get");
    }


    @Override
    public void onLastItemVisible() {
//        if (!mHasMore) {
//            return;
//        }
//
//        if (!mIsLoadingMore && mHasMore) {
//            listView.addFooterView(footView);
//            listView.setSelection(listView.getBottom());
//            isRefresh = false;
//            mIsLoadingMore = true;
//            mPage++;
//            updateData();
//        }
    }

    boolean isFristLoading = true;

    @Override
    public void onRefresh(PullToRefreshBase<ListView> refreshView) {
        if (!isFristLoading) {
            String label =
                    "更新时间:" + DateUtils.formatDateTime(this, System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME
                            | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
            refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
        }
        isFristLoading = false;
        refresh();
    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (position == 0) return;
        Intent i = new Intent(this, BuyCarVipActivity.class);
        i.putExtra("isFromRegister", true);
        startActivity(i);
    }

    @Override
    public void onDataJsonError(String errorMessage) {
        if (!isRefresh && mIsLoadingMore) {
            listView.removeFooterView(footView);
        }
        mIsLoadingMore = false;
        Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT).show();
        pullToRefreshListView.onRefreshComplete();
    }

    @Override
    public void onDataJsonUpdate(JSONObject json) {
        if (!isRefresh && mIsLoadingMore) {
            listView.removeFooterView(footView);
        }
        JSONArray jsonArray = null;
        if (isRefresh) {
            list.clear();
            adapter.setData(list);
        }
        try {
            jsonArray = json.getJSONArray("data");
            if (0 == jsonArray.length()) {
                mIsLoadingMore = false;
                nodataImageView.setVisibility(View.VISIBLE);
                pullToRefreshListView.onRefreshComplete();
                return;
            }

            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jo = jsonArray.getJSONObject(i);
                list.add(jo);

            }
//            int page_num = json.getInt("total_page");
//            if (page_num == mPage) {
//                mHasMore = false;
//            }
        } catch (JSONException e) {
            mIsLoadingMore = false;
            nodataImageView.setVisibility(View.VISIBLE);
            Toast.makeText(this, "数据异常，请稍后再试", Toast.LENGTH_SHORT).show();
            pullToRefreshListView.onRefreshComplete();
            return;
        }
        adapter.setData(list);
        pullToRefreshListView.onRefreshComplete();
        mIsLoadingMore = false;
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mNetDataJson != null) {
            mNetDataJson.cancelTask();
            mNetDataJson = null;
        }
        if (deleteNetDataJson != null) {
            deleteNetDataJson.cancelTask();
            deleteNetDataJson = null;
        }
    }


}

